<script setup lang="ts">
import {ref, h, computed} from "vue";
import {DataTable, ActionColumns} from '@/components/DataTable'
import SearchParamCard from '@/components/SearchParamCard'
import {NTag, useMessage} from 'naive-ui'
import {PlusRound} from "@vicons/material";
import {checkPermissionForItems, hasAnyPermission} from '@/utils'
import {deleteRequest} from '@/api'
import AddEdit from "./components/add_edit.vue";
import {ModalType} from "@/utils/enums.ts";

const message = useMessage()

const statusOptions: Array<{ label: string; value: number }> = [
  {
    label: '正常',
    value: 0
  }, {
    label: '锁定',
    value: 1
  }
];

const searchParams = ref<{ key: string | null, status: number | null }>({
  key: '',
  status: null,
})
// 新增、编辑单数据
const addEditFormVisible = ref(false);
const currentEditData = ref<Recordable>({});
//数据表
const admins_list = ref<InstanceType<typeof DataTable> | null>(null);
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 70,
    align: 'center',
    resizable: false
  },
  {
    title: '账号',
    key: 'account',
    minWidth: 120,
  },
  {
    title: '昵称',
    key: 'nickname',
    minWidth: 120,
  },
  {
    title: '角色',
    key:'role_name',
    render: (row: { is_super: boolean, role_name: string }) => {
      return row.is_super ? '超级管理员' : row.role_name
    }
  },
  {
    title: '电话',
    key: 'phone',
    width: 130,
  }, {
    title: 'E-mail',
    key: 'email',
  }, {
    title: '状态',
    key: 'is_locked',
    width: 80,
    align: 'center',
    resizable: false,
    render: (row: { is_locked: number }) => {
      const locked_txt = statusOptions.find((t) => t.value === row.is_locked);
      return h(NTag,
          {
            type: row.is_locked == 0 ? 'success' : 'error',
          },
          {
            default: () => (locked_txt && locked_txt.label),
          }
      );
    }
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 175,
  }
]

//操作列及权限
const actionPermission = ['admin:edit', 'admin:delete']
const displayedActions = computed(() => {
  return checkPermissionForItems(
      actionPermission.map(p => ({perm: p})),
      obj => obj.perm
  )
})

const actionColumnWidth = computed(() => {
  const trueCount = displayedActions.value.filter(item => item).length;
  if (trueCount == 1) {
    return 50
  } else {
    return 90
  }
})

const showActionColumn = computed(() => hasAnyPermission(actionPermission))
const operationColumns = computed(() => {
  return {
    width: actionColumnWidth.value,
    isShow: showActionColumn.value,
    render(row: Recordable) {
      return h(ActionColumns, {
        actions: [
          {
            label: '编辑',
            type: 'primary',
            permission: actionPermission[0],
            disabled: row.is_disabled as unknown as boolean,
            onClick: () => {
              currentEditData.value = {
                id: row.id,
                account: row.account,
                nickname: row.nickname,
                phone: row.phone,
                email: row.email,
                is_locked: row.is_locked,
                role: row.role,
              };
              addEditFormVisible.value = true;
            }
          },
          {
            label: '删除',
            type: 'error',
            permission: actionPermission[1],
            disabled: row.is_disabled as unknown as boolean,
            popConfirm: {
              content: `确定删除当前账号(管理员)吗？`,
              onPositiveClick: () => {
                deleteRequest('/admins/delete', row.id).then((res) => {
                  if (res.code == 200) {
                    message.success(res.message, {
                      duration: 1500,
                      onLeave() {
                        admins_list.value?.reload()
                      }
                    })
                  } else {
                    message.error(res.message || '删除失败！')
                  }
                })
              },
            }
          },
        ],
      })
    }
  }
})

//查询数据
const searchData = () => {
  admins_list.value?.searchData()
}

//关闭模态框
const handleModalClose = (modalType: ModalType) => {
  if (!admins_list.value) return
  if (modalType === ModalType.SEARCH) {
    admins_list.value.searchData?.()
  } else {
    admins_list.value.reload?.()
  }
}
</script>

<template>
  <div>
    <search-param-card @onSearch="searchData" @onReset="()=>(searchParams.key='',searchParams.status=null)">
      <template #default>
        <n-form-item>
          <n-input v-model:value="searchParams.key" placeholder="请输入关键字..." clearable/>
        </n-form-item>
        <n-form-item>
          <n-select v-model:value="searchParams.status" :options="statusOptions" placeholder="请选择状态"
                    style="width: 110px" clearable/>
        </n-form-item>
      </template>
    </search-param-card>
    <n-card>
      <data-table ref="admins_list"
                  :columns="columns"
                  :action-column="operationColumns"
                  :params="searchParams"
                  url="/admins/lists">
        <template #toolBarLeft>
          <n-button type="primary" ghost v-permission="['admin:save']" @click="()=>(addEditFormVisible=true)">
            <template #icon>
              <n-icon>
                <PlusRound/>
              </n-icon>
            </template>
            新增
          </n-button>
        </template>
      </data-table>
    </n-card>
    <!--  新增、编辑  -->
    <component :is="AddEdit"
               v-model:visible="addEditFormVisible"
               :form-data="currentEditData"
               @close-modal="handleModalClose"/>
  </div>
</template>

<style scoped lang="scss">

</style>

